﻿using SuperSocket.SocketBase;
using SuperSocket.WebSocket;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SuperSocket1._6.Core
{
    public class WebSockSvr
    {
        public List<WebSocketSession> ClinetList { get; set; } = new List<WebSocketSession>();
        private WebSocketServer server;
        public WebSockSvr()
        {
            server = new WebSocketServer();
            server.NewMessageReceived += Ws_NewMessageReceived;//当有信息传入时
            server.NewSessionConnected += Ws_NewSessionConnected;//当有用户连入时
            server.SessionClosed += Ws_SessionClosed;//当有用户退出时
            server.NewDataReceived += Ws_NewDataReceived;//当有数据传入时
        }

        public void Start()
        {
            if (server.Setup(4040))//绑定端口
                server.Start();//启动服务  
        }

        //public void SendDatas()
        //{
        //    //对当前已连接的所有会话进行广播
        //    foreach (var session in server.GetAllSessions())
        //    {
        //        session.Send($"Dev[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}, 12.34, 34.56, 56.78, \"77705683\"]");
        //        Thread.Sleep(1000);
        //    }
        //}
        public void SendDatas()
        {
            for (int i = 0; i < 200; i++)
            {
                Task.Run(async () =>
                {
                    while (true)
                    {
                        try
                        {
                            for (int j = 0; j < ClinetList.Count; j++)
                            {
                                var sock = ClinetList[j];
                                if (sock.Connected)
                                {
                                    sock.TrySend($"Dev[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}, 12.34, 34.56, 56.78, \"77705683\"]");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("出现异常：" + ex.Message + "\r\n" + ex.StackTrace);
                        }
                        finally
                        {
                            await Task.Delay(10);
                        }
                    }
                });
            }

        }

        private void Ws_NewSessionConnected(WebSocketSession session)
        {
            ClinetList.Add(session);
        }

        private void Ws_NewMessageReceived(WebSocketSession session, string value)
        {

        }

        private void Ws_SessionClosed(WebSocketSession session, CloseReason value)
        {
            ClinetList.Remove(session);
        }

        private void Ws_NewDataReceived(WebSocketSession session, byte[] value)
        {

        }
    }
}
